package org.tinygame.herostory.login;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tinygame.herostory.MySqlSessionFactory;
import org.tinygame.herostory.async.AsyncOperationProcessor;
import org.tinygame.herostory.async.IAsyncOperation;
import org.tinygame.herostory.login.db.IUserDao;
import org.tinygame.herostory.login.db.UserEntity;
import org.tinygame.herostory.util.RedisUtil;
import redis.clients.jedis.Jedis;

import java.util.function.Function;

/**
 * @author anan
 * @create 2022-05-06 0:50
 */
public class LoginService {
    static private final Logger LOGGER = LoggerFactory.getLogger(LoginService.class);

    static private final LoginService _instance = new LoginService();

    private LoginService(){}

    public static LoginService getInstance() {
        return _instance;
    }

    public void userLogin(String userName, String password, Function<UserEntity, Void> callback){
        if(null == userName || null == password){
            return;
        }
        AsyncOperationProcessor.getInstance().process(new AsyncGetUserEntity(userName, password){
            @Override
            public void doFinish() {
                if(null != callback){
                    callback.apply(this.getUserEntity());
                }
            }
        });
    }

    private void updateBasicInfoInRedis(UserEntity userEntity){
        if(null == userEntity) return;

        try(Jedis jedis = RedisUtil.getJedis()) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userName", userEntity.getUserName());
            jsonObject.put("heroAvatar", userEntity.getHeroAvatar());

            jedis.hset("User_" + userEntity.userId, "BasicInfo", jsonObject.toJSONString());
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    private class AsyncGetUserEntity implements IAsyncOperation{
        private final String _userName;

        private final String _password;

        private UserEntity _userEntity;

        AsyncGetUserEntity(String userName, String password){
            this._userName = userName;
            this._password = password;
        }

        UserEntity getUserEntity(){
            return _userEntity;
        }

        @Override
        public int getBindId(){
            if(null == _userName) return 0;
            else {
                return _userName.charAt(_userName.length() - 1);
            }
        }



        @Override
        public void doAsync() {
            try (SqlSession sqlSession = MySqlSessionFactory.openSession()){
                LOGGER.info("当前线程 = {}", Thread.currentThread().getName());
                IUserDao dao = sqlSession.getMapper(IUserDao.class);
                UserEntity userEntity = dao.getUserByName(_userName);
                if(null != userEntity){
                    if(!_password.equals(userEntity.getPassword())){
                        throw new RuntimeException("用户密码错误");
                    }
                }
                else{
                    userEntity = new UserEntity();
                    userEntity.setUserName(_userName);
                    userEntity.setPassword(_password);
                    userEntity.setHeroAvatar("Hero_Shaman");
                    dao.insertInto(userEntity);
                }
                LoginService.getInstance().updateBasicInfoInRedis(userEntity);
                _userEntity = userEntity;

            }catch (Exception e){
                LOGGER.error(e.getMessage(), e);
            }
        }
    }
}
